package com.jxc.config;

import java.io.IOException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;

@Configuration
@MapperScan(basePackages="com.jxc.model.mapper", sqlSessionFactoryRef="jxcSessionFactory")
public class DataSourceConfig {

	@Value("${spring.datasource.mybatis.mapperpath}")
	private String mapperPath;
	
	@Autowired
	private ResourcePatternResolver resourcePatternResolver;
	
	@Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource buildDataSource() {
        return DataSourceBuilder.create().build();
    }
	
	@Bean
	public SqlSessionFactory jxcSessionFactory(){
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setDataSource(buildDataSource());
		try {
			Resource[] resources = resourcePatternResolver.getResources(mapperPath);
			factoryBean.setMapperLocations(resources);
			factoryBean.afterPropertiesSet();
			return factoryBean.getObject();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Bean
	public SqlSessionTemplate footballSessionTemplate(){
		SqlSessionTemplate template = new SqlSessionTemplate(jxcSessionFactory());
		return template;
	}
}
